var BSTMG = BSTMG || {};
BSTMG.common = {
    init: function() {
        var that = this;
        /* 显示当前页菜单 */
        that.showCurrentMenu();
    },
    showCurrentMenu: function() {
        //菜单打开功能增加，打开当前页的菜单
        var $menu = $(".sidebar-menu > .treeview > a");
        if (typeof(currentMenu) !== "undefined") {
            var currentmenu = $.trim(currentMenu);
            $menu.each(function() {
                var $this = $(this);
                if ($this.hasClass(currentmenu)) {
                    //$this.trigger('click');
                    $this.next('.treeview-menu').show();
                    $this.parent('.treeview').data('isActive', true).addClass("active");
                    $this.children(".fa-angle-left").first().removeClass("fa-angle-left").addClass("fa-angle-down");
                }
            });
        } else {
            if (window.console) {
                console.warn('左侧菜单打开页必须定义变量');
            }
        }
    },
    hjhPages: function(url,args,callback) {
    	var prepareHTML = '<div class="row"><div class="col-xs-4"><div class="dataTables_info"id="pageInfor">当前显示数据<select class="form-control input-sm showCountAstrict"><option value="5">5</option><option value="10">10</option><option value="20">20</option><option value="30">30</option><option value="40">40</option><option value="50">50</option></select>条，共<b class="allCount">0</b>条</div></div><div class="col-xs-8"><div class="dataTables_paginate paging_bootstrap text-right"><ul class="pagination"><li><a href="#"data-goto="1">1</a></li></ul></div></div></div>',
			$pagebox = $("#pagesbox");
    	if($.isFunction(args)){
    		callback = args;
    		args={};
    		//console.log('第二个参数是函数');
    	}
        //添加到文档中
    	$pagebox.html(prepareHTML);
        var that = this,
            $pageinfor = $pagebox.find("#pageInfor"),
            $astrict = $pageinfor.find(".showCountAstrict"),
            $all = $pageinfor.find(".allCount"),
            $pagebutton = $pagebox.find(".pagination");
        var last = $.trim($astrict.val()),
            all = $.trim($all.text()),
            pagecount = Math.ceil(all / last);
        $pagebutton.on('click', 'li a', function() {
            var $this = $(this),
                go = $.trim($this.attr("data-goto")), //点击的位置
                current = 0; //当前的位置
            last = $.trim($astrict.val()); //一次获取的数据量
            pagecount = Math.ceil($.trim($all.text()) / $.trim($astrict.val())); //获取分页总数
            //防止重复提交
            var isActive = $this.parent('li').hasClass('active');
            if (isActive) {
                return false;
            }

            $pagebutton.children('li').each(function() {
                var $this = $(this);
                if ($this.hasClass('active')) {
                    current = parseInt($this.children('a').attr("data-goto"));
                }
            });
            if (go == 'prev' || go == 'next') {
                go = go == 'prev' ? --current : ++current;
                switch (go) {
                    case 0:
                        BSTYUN.dialog.warn('当前已是第一页！');
                        return false;
                        break;
                    case pagecount + 1:
                        BSTYUN.dialog.warn('当前已是最后一页！');
                        return false;
                        break;
                }
            };
            go = parseInt(go);
            var params = $.extend({},{page: go,last: last},args);
            $.ajax({
                url: url,
                type: 'post',
                dataType: 'json',
                data: params,
                success: function(data) {
                	
                	callback && callback(data);
                	
                	$all.text(data.totalRows);					//更新数据总量
                    adjustPageButton(go, last, data.totalRows);	//调整下面的按钮
                },
                error: function(event) {
                    BSTYUN.dialog.warn('网络异常，请稍后尝试');
                }
            });
            return false;
        });
        $astrict.on('change', function() {
            var $this = $(this),
                last = parseInt($this.val()),
                totalRows = parseInt($all.val());
            adjustPageButton(1,$.trim($astrict.val()),$.trim($all.text()));
            $pagebutton.children('li').eq(1).removeClass('active').children('a').trigger('click');
        });
        
        //默认显示第一页,html代码必须有第一页的a标签。
        $pagebutton.find('li a').trigger('click');
        
        function adjustPageButton(current,last,all){
    		var $buttons = $pagebutton,
    			pagecount = Math.ceil(all/last),
    			html = '<li class="prev"><a href="#" data-goto="prev">← 上一页</a></li>',
    			temple = '',
    			isten = 0;
    			if(current < 11){
    				for(var i = 1; i <= current + Math.abs(11 - current); i++){
    					if(i > pagecount){break;}
    					if(current == 1 && i == 1){
    						html = '<li class="prev disabled"><a href="#" data-goto="prev">← 上一页</a></li>';
    					}
    					i == current ?
    					html += '<li class="active"><a href="#" data-goto="'+i+'">'+i+'</a></li>' :
    					html += '<li><a href="#" data-goto="'+i+'">'+i+'</a></li>';
    				}
    			}else{
    				var diff = Math.abs(pagecount - current);
    				if(diff < 8){
    					for(var i = current - (8 - diff); i < (current+8); i++){
    						if(i > pagecount){break;}
    						i == current ?
    						html += '<li class="active"><a href="#" data-goto="'+i+'">'+i+'</a></li>' :
    						html += '<li><a href="#" data-goto="'+i+'">'+i+'</a></li>';
    					}
    				}else{
    					for(var i = current - 2; i < (current+8); i++){
    						if(i > pagecount){break;}
    						i == current ?
    						html += '<li class="active"><a href="#" data-goto="'+i+'">'+i+'</a></li>' :
    						html += '<li><a href="#" data-goto="'+i+'">'+i+'</a></li>';
    					}
    				}
    			}
    		current == pagecount ? 
    		html += '<li class="next disabled"><a href="#" data-goto="next">下一页 → </a></li>'	:
    		html += '<li class="next"><a href="#" data-goto="next">下一页 → </a></li>';
    		$buttons.empty().html(html);
    	}
    }
}
BSTMG.tools = {
    //检测非空
    checkNull: function(para) {
        return para == null ? '' : para;
    }
}
$(function() {
    BSTMG.common.init();
});